//
//  AppListViewController.m
//  LittleSugar
//
//  Created by zhang on 15-6-13.
//  Copyright (c) 2015年 张鑫. All rights reserved.
//

#import "AppListViewController.h"
#import "AFNetworking.h"
#import "JHRefresh.h"
#import "HomeCell.h"
#import "HomeModel.h"
#import "HomeViewController.h"
#import "CategoryViewController.h"
#import "CollectViewController.h"
#import "AdView.h"


@interface AppListViewController ()
{
    NSMutableArray *_bannerArr;
    UIPageControl *_pageControl;
}
    @property(nonatomic,strong)UIPageControl *pageControl;
    @property (nonatomic,strong) NSMutableArray *imageNames;
    @property (nonatomic,strong) NSMutableArray *bannerArr;
    @property (nonatomic,strong) NSMutableArray *textArr;
@end

@implementation AppListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navigationbar"] forBarMetrics:UIBarMetricsDefault];
    [self addTitleViewWithTitle:self.title];
    //[self addItemWithTitle:nil target:self action:@selector(leftClick:) isLeft:YES];
    //[self addItemWithTitle:nil target:self action:@selector(rightClick:) isLeft:NO];
    
    [self creatTableView];
    
    //创建af
    _manager = [AFHTTPRequestOperationManager manager];
    //响应格式 二进制 不解析
    _manager.responseSerializer  = [AFHTTPResponseSerializer serializer];

}
#pragma mark - 加滚动新闻
-(void)addAdView:(NSMutableArray *)imageNames textArr:(NSMutableArray *)textArr{
    AdView *adView = [[AdView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 150)];
    adView.textArr = textArr;
    
    adView.imageNames = imageNames;
    
    self.tableView.tableHeaderView = adView;
    
    //self.tableView.showsHorizontalScrollIndicator = NO;
}


#pragma mark - tableView
- (void)creatTableView {
    self.dataArr = [[NSMutableArray alloc] init];
    self.textArr = [NSMutableArray array];
    _imageNames = [[NSMutableArray alloc] init];
    //self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 150;
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:@"HomeCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
}

#pragma mark - 刷新
//刷新
- (void)creatRefreshView{//在子类中调用 如果不适合子类那么重写
   
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.currentPage = 1;
        weakSelf.update_time = 0;
        weakSelf.isRefreshing = YES;
        [weakSelf addTaskUrl:kHomeUrl isRefresh:YES];
    }];
    
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //上拉加载更多
        if (weakSelf.isLoadMoring) {
            return ;
        }
        HomeModel *model = weakSelf.dataArr.lastObject;
        weakSelf.isLoadMoring = YES;
         weakSelf.currentPage++;
        weakSelf.update_time = model.update_time;
        [weakSelf addTaskUrl:kHomeUrl isRefresh:YES];
        
    }];
    
    
}
//结束刷新
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
    if (self.isLoadMoring) {
        self.isLoadMoring = NO;
        [self.tableView footerEndRefreshing];
    }
}


- (void)firstDownload {
    self.currentPage = 1;
    self.update_time = 0;
    self.isRefreshing = NO;
    self.isLoadMoring = NO;
    [self addTaskUrl:kHomeUrl isRefresh:YES];
}

- (void)addTaskUrl:(NSString *)url isRefresh:(BOOL)isRefresh {
    url = [NSString stringWithFormat:kHomeUrl,self.update_time];
    __weak typeof (self) weakSelf = self;
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
        if (responseObject) {
            if (weakSelf.currentPage == 1) {
                [weakSelf.dataArr removeAllObjects];
            }
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = dict[@"data"];
            NSArray *bannerArr = dataDict[@"banner"];
            NSArray *topicArr = dataDict[@"topic"];
            //遍历数组解析
            for (NSDictionary *appDict in topicArr) {
                HomeModel *model = [[HomeModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:appDict];
                [weakSelf.dataArr addObject:model];
            }
            if (weakSelf.imageNames) {
                [weakSelf.imageNames removeAllObjects];
            }
            
            for (NSDictionary *appDict in bannerArr) {
                HomeModel *model = [[HomeModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:appDict];
                [weakSelf.textArr addObject:model.title];
                [weakSelf.imageNames addObject:model.photo];
            }
            [weakSelf addAdView:weakSelf.imageNames textArr:weakSelf.textArr];
            //[weakSelf createPageControlWithArr:weakSelf.imageNames];
        }
        
        [weakSelf.tableView reloadData];
        [weakSelf endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        //结束刷新
        [weakSelf endRefreshing];
    }];
    
}
//- (void)createHeadLabelWithArr:(NSArray *)arr {
//    UILabel *label1 = [MyControl creatLabelWithFrame:CGRectMake(kScreenSize.width-80-10, 120, 50, 10) text:[NSString stringWithFormat:[NSString stringWithFormat:@"%ld",arr]]];
//    UILabel *label2 = [MyControl creatLabelWithFrame:CGRectMake(kScreenSize.width-80, 120, 50, 30) text:[NSString stringWithFormat:@"/%ld",arr.count]];
//}

//- (void)createPageControlWithArr:(NSArray *)arr {
//    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(kScreenSize.width/2-60, 120, 120, 30)];
//        _pageControl.numberOfPages = arr.count;
//        _pageControl.tag = 301;
//        [_pageControl addTarget:self action:@selector(pageControl:) forControlEvents:UIControlEventValueChanged];
//
//        [self.tableView addSubview:_pageControl];
//}

////控制滚动
//- (void)pageControl:(UIPageControl *)page{
//    [self.tableView.tableHeaderView setContentOffset:CGPointMake(_pageControl.currentPage*320, 0) animated:YES];
//
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    CGPoint point = scrollView.contentOffset;
//    _pageControl.currentPage = point.x/320;
//
//}
//
//
//- (void)pageClick:(UIPageControl *)page {
//    [self.tableView scrollRectToVisible:CGRectMake(page.currentPage*kScreenSize.width, 0, kScreenSize.width, kScreenSize.height) animated:YES];
//}


- (void)leftClick:(UIButton *)button {
    
}

- (void)rightClick:(UIButton *)button {
    
}

#pragma mark - tableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeCell" forIndexPath:indexPath];
    HomeModel *model = self.dataArr[indexPath.row];
    [cell showDataWithModel:model indexPath:indexPath];
    return cell;
}

#pragma mark - 选中cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //HomeModel *model = _dataArr[indexPath.row];
    NSLog(@"oooo");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
